package com.neusoft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.neusoft.base.BaseServiceImpl;
import com.neusoft.config.Pagination;
import com.neusoft.mapper.FulllessMapper;
import com.neusoft.mapper.ItemMapper;
import com.neusoft.model.ActivitySearch;
import com.neusoft.po.Fullless;
import com.neusoft.po.Item;
import com.neusoft.service.FulllessService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FulllessServiceImpl extends BaseServiceImpl<Fullless> implements FulllessService {

    @Resource
    private FulllessMapper fulllessMapper;
    @Resource
    private ItemMapper itemMapper;

    @Override
    public BaseMapper<Fullless> getBaseDao() {
        return fulllessMapper;
    }

    @Override
    public Integer save(Fullless entity) {
        Integer id = entity.getId();
        if (null == id) {
            entity.setCreate_time(new Date());
            insert(entity);
            id = entity.getId();
        } else {
            entity.setUpdate_time(new Date());
            updateById(entity);
            fulllessMapper.setNullByFullless(id);
        }
        if (null != entity.getItem_ids() && entity.getItem_ids().length > 0) {
            itemMapper.setFullless(entity.getItem_ids(), id);
        }
        return id;
    }

    @Override
    @Pagination
    public Object page(ActivitySearch pageSearch) {
        List<Fullless> list = fulllessMapper.list(pageSearch.getDescription());
        list.forEach(li -> {
            List<Integer> item_ids = itemMapper.selectList(new QueryWrapper<Item>().eq("fullless_id", li.getId()))
                    .stream().map(Item::getId).collect(Collectors.toList());
            li.setItem_ids(item_ids.toArray(new Integer[]{}));
        });
        return list;
    }

    @Override
    public Integer delete(Integer[] ids) {
        itemMapper.setNullFullless(ids);
        deleteByIds(ids);
        return ids.length;
    }


}
